from django.shortcuts import render,redirect
from App001 import  models
from django.core.validators import ValidationError
from django.core.validators import RegexValidator
# from App001.views import depart
# Create your views here.
def user_list(request):
    """用户管理"""
    quary=models.UserInfo.objects.all()
    return  render(request,'user_list.html',{"quary":quary})

def user_add(request):
    """用户的添加"""
    context={
        'gender':models.UserInfo.gender_choices,
        "depart_list":models.Department.objects.all()
    }

    return render(request,"user_add.html",context)
from django import forms
class UserModelForm(forms.ModelForm):
    # password= forms.CharField(min_length=2,label="密码")
    # validators 是可以对密码来写正则表达式
    class Meta:
        model = models.UserInfo
        fields=["name","password","age","account","create_time","gender","depart"]
        #
        widgets={
            #通过属性去定义这些框框的形状
            "name":forms.TextInput(attrs={"class":"form-control"}),
            "password": forms.TextInput(attrs={"class": "form-control"}),
            "age": forms.TextInput(attrs={"class": "form-control"}),
            "account": forms.TextInput(attrs={"class": "form-control"}),
            "gender": forms.Select(attrs={"class": "form-control"}) ,
            "create_time": forms.TextInput(attrs={"class": "form-control"}),
            "depart": forms.Select(attrs={"class": "form-control"}),

           # 关于这个model这个东西应该进行系统的研究一下

        }
        # def __init__(self,*args,**kwargs):
        #     super().__init__(*args,**kwargs)
        #
        #     for name , field in self.fields.items():
        #         field.widgets.attrs ={"class":"form-control","placeholder":field.labels}
def user_model_form_add(request):
    """进行用户的添加，(ModelForm版本)"""
    if request.method=="GET":
       form=UserModelForm()
       return render(request,"user_model_form_add.html",{'form':form})

    #用户使用post请求来进行校验数据：
    form=UserModelForm(data=request.POST)
    if form.is_valid():
        #进行数据的校验，然后进行保存
        form.save() #保存直接到数据库
        return redirect('/user/list/')
    else:
        #返回这个页面，然后通过前端的部分去进行错误信息展示
        return render(request, "user_model_form_add.html", {'form': form})

def user_edit(request,nid):
    """进行用户的数据进行更改"""
    row_object= models.UserInfo.objects.filter(id=nid).first()
    if request.method=="GET":
        form=UserModelForm(instance=row_object)
        return render(request,"user_edit.html", {'form': form})
    form = UserModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, "user_edit.html", {'form': form})
def user_delete(request,nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')
